package com.example.secondhandmall.activity;

import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.secondhandmall.R;
import com.example.secondhandmall.api.Api;
import com.example.secondhandmall.api.ApiConfig;
import com.example.secondhandmall.api.MyCallback;
import com.example.secondhandmall.entity.BaseResponse;
import com.example.secondhandmall.entity.GoodsEntity;
import com.example.secondhandmall.entity.GoodsResponse;
import com.example.secondhandmall.entity.GoodsSimpleEntity;
import com.example.secondhandmall.entity.LoginResponse;
import com.example.secondhandmall.view.CircleCornerTransForm;
import com.example.secondhandmall.view.CircleTransform;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.HashMap;

public class DetailActivity extends BaseActivity {

    private TextView tvTopTitle;
    private ImageView ivAvatar;
    private TextView tvName;
    private TextView tvPrice;
    private TextView tvTitle;
    private TextView tvDetail;
    private ImageView ivImg;
    private Button btnCancel;
    private ImageView ivCollect;
    private TextView tvCollect;
    private Button btnBuy;
    private ImageView ivReturn;

//    GoodsEntity goodsEntity;

    private Boolean collectFlag;
    private int id;
    private TextView tvAddress;
    private String account;
//    private HashMap detail;
//    private String name;
//    private GoodsSimpleEntity goodsSimpleEntity;
    private int del;

    private GoodsEntity goodsEntity;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
//            goodsAdapter.setDatas(datas);
//            goodsAdapter.notifyDataSetChanged();
            switch (msg.what) {
                case 0:
                    tvTopTitle.setText(goodsEntity.getGoodsName());
//        ivAvatar.setImageURI(Uri.parse(goodsEntity.getAvatarurl()));
                    tvName.setText(goodsEntity.getUserId());//这个接口没name就从列表那连着id传进来
                    tvPrice.setText(String.valueOf(goodsEntity.getGoodsPrice()));
                    tvTitle.setText(goodsEntity.getGoodsName());
                    tvDetail.setText(goodsEntity.getGoodsSignature());
//        ivImg.setImageURI(Uri.parse(goodsEntity.getImgurl()));

                    Picasso.with(mContext)
                            .load(goodsEntity.getUserPhoto())
                            .transform(new CircleTransform())
                            .into(ivAvatar);
                    Picasso.with(mContext)
                            .load(goodsEntity.getPhotoUrls().get(0).getGoodsPhotoUrl())
                            .transform(new CircleCornerTransForm())
                            .into(ivImg);

//                    id = goodsEntity.getId();
                    collectFlag = goodsEntity.isIsCollect();
                    tvAddress.setText(goodsEntity.getGoodsAddress());
                    del = goodsEntity.getDel();

                    if (collectFlag) {
                        tvCollect.setTextColor(Color.parseColor("#f1eb2e"));
                        ivCollect.setImageResource(R.mipmap.collect_selected);
                    }//数据渲染放请求之后
                    break;
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.activity_detail;
    }

    @Override
    protected void initView() {
        tvTopTitle = findViewById(R.id.tv_top_title);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvName = findViewById(R.id.tv_name);
        tvPrice = findViewById(R.id.tv_price);
        tvTitle = findViewById(R.id.tv_title);
        tvDetail = findViewById(R.id.tv_detail);
        ivImg = findViewById(R.id.iv_img);
        btnCancel = findViewById(R.id.btn_cancel);
        ivCollect = findViewById(R.id.iv_collect);
        tvCollect = findViewById(R.id.tv_collect);
        btnBuy = findViewById(R.id.btn_buy);
        ivReturn = findViewById(R.id.iv_return);
        tvAddress = findViewById(R.id.tv_address);
    }

    @Override
    protected void initData() {
        id = (int) getIntent().getSerializableExtra("detail");
//        detail = (HashMap) getIntent().getSerializableExtra("detail");
//        id = (int)detail.get("id");
//        name = (String) detail.get("name");
        account = getStringFromSp("account");
        showDetail();
//        tvTopTitle.setText(goodsEntity.getTitle());
////        ivAvatar.setImageURI(Uri.parse(goodsEntity.getAvatarurl()));
//        tvName.setText(goodsEntity.getName());
//        tvPrice.setText(goodsEntity.getPrice());
//        tvTitle.setText(goodsEntity.getTitle());
//        tvDetail.setText(goodsEntity.getDetail());
////        ivImg.setImageURI(Uri.parse(goodsEntity.getImgurl()));
//
//        Picasso.with(mContext)
//                .load(goodsEntity.getAvatarurl())
//                .transform(new CircleTransform())
//                .into(ivAvatar);
//        Picasso.with(mContext)
//                .load(goodsEntity.getImgurl())
//                .transform(new CircleCornerTransForm())
//                .into(ivImg);
//
//        id = goodsEntity.getId();
//        collectFlag = goodsEntity.getCollectFlag();
//        tvAddress.setText(goodsEntity.getAddress());
//
//        if (collectFlag) {
//            tvCollect.setTextColor(Color.parseColor("#f1eb2e"));
//            ivCollect.setImageResource(R.mipmap.collect_selected);
//        }//数据渲染放请求之后

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect();
            }
        });
        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(del==0)
                buy();
                else showToast("该物品已经被购买！");
            }
        });
        ivReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void buy() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("goodsId",id);
        params.put("userId",account);
        Api.config(ApiConfig.OrderList,params).postApendRequest(new MyCallback() {
            @Override
            public void onSuccess(String res) {
                System.out.println(res);
                LoginResponse buyResponse = new Gson().fromJson(res,LoginResponse.class);
                if(buyResponse.getCode()==200&&buyResponse.isData()){
                    showToastSync("购买成功！");
                }
            }

            @Override
            public void onFailure(Exception e) {
showToastSync("购买失败！");
            }
        });
    }

    private void collect() {
        if (collectFlag) {
            tvCollect.setTextColor(Color.parseColor("#000000"));
            ivCollect.setImageResource(R.mipmap.collect);

            //        String account = getStringFromSp("account");
            HashMap<String, Object> params = new HashMap<>();
//            params.put("account", account);
//            params.put("id", id);
//            params.put("flag", !collectFlag);
            params.put("goodsId",id);
            params.put("userId",account);
            Api.config(ApiConfig.DELETE_COLLECT, params).deleteRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    LoginResponse collectResponse = new Gson().fromJson(res, LoginResponse.class);
                    if (collectResponse.getCode() == 200&&collectResponse.isData()) {
//                    if (collectFlag) {
//                        tvCollect.setTextColor(Color.parseColor("#000000"));
//                        ivCollect.setImageResource(R.mipmap.collect);
//                    } else {
//                        tvCollect.setTextColor(Color.parseColor("#f1eb2e"));
//                        ivCollect.setImageResource(R.mipmap.collect_selected);
//                    }
//                    collectFlag = !collectFlag;
                        showToastSync("取消收藏成功！");
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToastSync("取消收藏失败！");
                }
            });
        } else {
            tvCollect.setTextColor(Color.parseColor("#f1eb2e"));
            ivCollect.setImageResource(R.mipmap.collect_selected);
            HashMap<String, Object> params = new HashMap<>();
            params.put("goodsId",id);
            params.put("userId",account);
            Api.config(ApiConfig.COLLECT, params).postApendRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    LoginResponse collectResponse = new Gson().fromJson(res, LoginResponse.class);
                    if (collectResponse.getCode() == 200&&collectResponse.isData()) {
                        showToastSync("收藏成功！");
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToastSync("收藏失败！");
                }
            });
        }
        collectFlag = !collectFlag;
    }

    private void showDetail() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("id",id);
        params.put("userId",account);
        Api.config(ApiConfig.GOODS_BY_ID,params).getRequest(new MyCallback() {
            @Override
            public void onSuccess(String res) {
                System.out.println(res);
                Gson gson = new Gson();
                GoodsResponse goodsResponse = gson.fromJson(res,GoodsResponse.class);
                if(goodsResponse.getCode()==200){
                    goodsEntity = goodsResponse.getData();
                    mHandler.sendEmptyMessage(0);
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure",e.toString());
                showToastSync("请求失败！");//也可以加个刷新
            }
        });
    }
}